<!--
 * @Author: 陈俊升 761723995@qq.com
 * @Date: 2023-12-19 13:30:36
 * @LastEditors: 陈俊升 761723995@qq.com
 * @LastEditTime: 2024-01-17 17:48:51
 * @FilePath: /hr_new_vue3/src/views/Management/Home/LeaveManagement/WorkHandover/Template/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%A工作交接
-->
<!-- 员工端-工作交接（待发起、待提交、待确认） -->
<template>
  <div class="template-steps">
    <a-steps changeable :current="current" @change="setCurrent">
      <a-step>交接基础信息</a-step>
      <a-step>编辑交接表内容</a-step>
      <a-step>确认发起</a-step>
    </a-steps>
  </div>
  <!-- 交接基础信息 -->
  <div v-show="current === 1" style="display: flex; justify-content: center">
    <BaseInfo ref="baseInfoRef" v-model:data="templateData.data" />
  </div>

  <!-- 编辑交接表内容 -->
  <div v-show="current === 2">
    <Design ref="designRef" v-model:data="templateData.data" />
  </div>
  <!-- 确认发起 -->
  <div v-show="current === 3" style="display: flex; justify-content: center">
    <Confirm ref="confirmRef" v-model:data="templateData.data" />
    <!-- <ContractPreview v-model:data="templateData.data" /> -->
  </div>
  <footer>
    <a-button
      class="btn"
      type="secondary"
      :disabled="current <= 1"
      @click="onPrev"
    >
      <IconLeft />
      上一步
    </a-button>
    <a-button
      class="btn"
      type="primary"
      v-show="current !== 3"
      :disabled="current >= 3"
      @click="onNext"
    >
      下一步
      <IconRight />
    </a-button>
    <a-button class="btn" type="outline" v-show="current === 3" @click="save">
      确认并保存
    </a-button>
    <a-button class="btn" type="primary" v-show="current === 3" @click="send">
      确认发起
    </a-button>
    <a-button class="btn" type="secondary" @click="router.back()">
      取消
    </a-button>
  </footer>
</template>

<script setup lang="ts">
import {
  SendWorkHandover,
  SaveWorkHandover,
  GetSendWorkHandleDetail,
  DelWorkHandleSub
} from '@/apis/management/human/baseSetting/leaveSetting';
import { cloneDeep } from 'lodash';
import { Message } from '@arco-design/web-vue';
import { GetHumanRosterDetail } from '@/apis/management/human/humanRoster';
import { useVModel } from '@vueuse/core';
import BaseInfo from './BaseInfo.vue';
import Design from './Design.vue';
import Confirm from './Confirm.vue';

const props = withDefaults(
  defineProps<{
    humanInfo: any; // 人员信息
    data: any; // 模板数据
  }>(),
  {}
);

const route = useRoute();
const router = useRouter();
const userId = +localStorage.getItem('userId');

let baseInfoRef = ref(); // 基础信息ref
let designRef = ref(); // 编辑ref
let confirmRef = ref(); // 确认ref
let pageHeaderSettingRef = ref();
let fileSettingRef = ref();

const templateData = reactive({
  data: {
    userData: {
      name: '',
      mobile: '',
      departmentName: '',
      positionName: '',
      superiorName: '',
      leaveTime: ''
    },
    baseInfo: {
      userId,
      userName: JSON.parse(localStorage.getItem('userInfo') || '{}').name,
      name: '',
      templateId: undefined,
      remark: '',
      confirmId: undefined, // 确认人id
      confirmName: undefined, // 确认人名称,
      status: 1 // 工作交接状态
    },
    designData: []
  }
});

let initTemplateData = cloneDeep(templateData.data); // 初始化的数据

watch(
  () => props.humanInfo,
  (n) => {
    if (n) {
      templateData.data.userData = n;
    }
  },
  {
    deep: true,
    immediate: true
  }
);

watch(
  () => props.data,
  (n) => {
    if (n.baseInfo.id) {
      templateData.data = cloneDeep(n);
      templateData.data.baseInfo.userName = JSON.parse(
        localStorage.getItem('userInfo') || '{}'
      )?.name;
    } else {
      templateData.data = cloneDeep(initTemplateData);
    }
  },
  {
    deep: true
  }
);

const current = ref(1);
const reset = () => {
  current.value = 1;
};
const onPrev = () => {
  current.value = Math.max(1, current.value - 1);
};
const onNext = async () => {
  // const check = await baseInfoRef.value.validate();
  // if (check) return;
  current.value = Math.min(4, current.value + 1);
  if (current.value > 1) {
    if (await checkValidate(baseInfoRef.value.validate)) {
      Message.error('请先填写必填信息！');
      current.value = 1;
      return;
    }
  }
  // if (current.value > 2) {
  //   if (await checkValidate(designRef.value.validate)) {
  //     console.log('====================================');
  //     console.log(designRef.value.formData);
  //     console.log('====================================');
  //     Message.error('请先填写必填信息！');
  //     current.value = 2;
  //     return;
  //   }
  // }
};
const setCurrent = async (n: number) => {
  current.value = n;
  if (current.value > 1) {
    if (await checkValidate(baseInfoRef.value.validate)) {
      current.value = 1;
      Message.error('请先填写必填信息！');
      return;
    }
  }
  if (current.value > 2) {
    if (await checkValidate(designRef.value.validate)) {
      console.log('====================================');
      console.log(designRef.value.formData);
      console.log('====================================');
      Message.error('请先填写必填信息！');
      current.value = 2;
      return;
    }
  }
};

const checkValidate = async (validate: any) => {
  if (await validate()) return true;
  else return false;
};

// 确认并保存
const save = async () => {
  try {
    if (await checkValidate(confirmRef.value.validate)) {
      Message.error('请先填写必填信息！');
      return;
    }
    let temp = cloneDeep(templateData.data);

    if (temp.baseInfo.id) {
      delete temp.designData;
      delete temp.userData;
      temp.baseInfo.status = 2;
      await SaveWorkHandover(temp);
      if (designRef.value.delIds.length > 0) {
        await DelWorkHandleSub({
          ids: designRef.value.delIds
        });
      }
    } else {
      delete temp.designData.baseInfo;
      temp.baseInfo.status = 2;
      const temp2 = {
        baseInfo: temp.baseInfo,
        ...temp.designData
      };
      await SendWorkHandover(temp2);
    }
    // router.back();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 确认发起
const send = async () => {
  try {
    try {
      if (await checkValidate(confirmRef.value.validate)) {
        Message.error('请先填写必填信息！');
        return;
      }
      let temp = cloneDeep(templateData.data);
      if (temp.baseInfo.id) {
        delete temp.designData;
        delete temp.userData;
        temp.baseInfo.status = 3;
        await SendWorkHandover(temp);
        if (designRef.value.delIds.length > 0) {
          await DelWorkHandleSub({
            ids: designRef.value.delIds
          });
        }
      } else {
        delete temp.designData.baseInfo;
        temp.baseInfo.status = 3;
        const temp2 = {
          baseInfo: temp.baseInfo,
          ...temp.designData
        };
        await SendWorkHandover(temp2);
      }
      // router.back();
    } catch (error: unknown) {
      console.log(error);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
</script>

<style lang="less" scoped>
.template-steps {
  padding: 0 160px;
  margin-bottom: 60px;
}
footer {
  height: 60px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    width: 120px;
    height: 40px;
    border-radius: 5px;
    margin-left: 10px;
  }
}
</style>
